package com.ltu.util.security;


import java.io.UnsupportedEncodingException;
import java.security.Key;  
import java.security.spec.AlgorithmParameterSpec;  
  
import javax.crypto.Cipher;  
import javax.crypto.SecretKeyFactory;  
import javax.crypto.spec.DESKeySpec;  
import javax.crypto.spec.IvParameterSpec; 



public class DESUtil {
	 private Key key;//密匙对象
	    private  byte[] DESkey;   //密匙
	    private byte[] DESIV = { 0x12, 0x34, 0x56, 0x78, (byte) 0x90, (byte) 0xAB,     //密匙的向量
	            (byte) 0xCD, (byte) 0xEF };    
	    private AlgorithmParameterSpec iv = null;// 加密算法的参数接口  
	    public DESUtil() {  
	        try {  
	        	//1.设置密匙
	        	this.DESkey="12345678".getBytes("UTF-8");
	        	//2.设置密匙参数
	        	DESKeySpec  keySpec=new DESKeySpec(DESkey);
	        	//3.获得密匙工厂
	        	 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
	        	//4.得到密匙对象
	        	 key = keyFactory.generateSecret(keySpec);
	        	//设置向量
	        	 System.out.println(new String(DESIV,"UTF-8"));
	        	 iv=new IvParameterSpec(DESIV);	        	 
	        } catch (Exception e) {  
	            e.printStackTrace();  
	        }  
	    } 
	    /** 
	     * 加密String 明文输入密文输出 
	     *  
	     * @param inputStr 
	     *            待加密的明文 
	     * @return outStr
	     * 			   加密后的字符串 
	     */  
	    public  String  getEnc(String inputStr){
	    	String  outStr="";
	    	byte[] mi=null;
	    	byte[] ming=null;
	    	try {
				ming=inputStr.getBytes("UTF-8");
				mi=this.getEncodeing(ming);
				byte[] temp=Base64.encode(mi,Base64.DEFAULT);
				outStr=new String(temp);
			} catch (UnsupportedEncodingException e) {

				e.printStackTrace();
			}finally{
				mi=null;
				ming=null;
			}
	    	
	    	return outStr;
	    }
	    /** 
	     * 加密以byte[]明文输入,byte[]密文输出 
	     *  
	     * @param bt 
	     *            待加密的字节码 
	     * @return 加密后的字节码 
	     */  
	    private byte[] getEncodeing(byte[] bt) {
			byte[]  result=null;
			Cipher  c;
			try {
				 c=Cipher.getInstance("DES/CBC/PKCS5Padding");
				 c.init(Cipher.ENCRYPT_MODE, key, iv);  
				 result = c.doFinal(bt);  
			} catch (Exception e) {

				e.printStackTrace();
			} finally{
				c=null;
			}
			
			return result;
		}
		public  String getDec(String inputStr){
	    	String outStr="";
	    	byte[] mi=null;
	    	byte[] ming=null;
	    	try {
				mi= Base64.decode(inputStr.getBytes(), Base64.DEFAULT);
				ming=this.getDesCodeing(mi);
				outStr=new String(ming,"UTF-8");
			} catch (UnsupportedEncodingException e) {

				e.printStackTrace();
			}finally{
				mi=null;
				ming=null;
			}
	    	return  outStr;
	    }
		private byte[] getDesCodeing(byte[] bt) {
			byte[]  result=null;
			Cipher  c;
			try {
				c=Cipher.getInstance("DES/CBC/PKCS5Padding");
				 c.init(Cipher.ENCRYPT_MODE, key, iv);  
				 result = c.doFinal(bt);  
			} catch (Exception e) {

				e.printStackTrace();
			} finally{
				c=null;
			}
			return result;
		}
		

}
